package cc.booku.owlbox.HomeDirectory;

import android.content.Intent;
import android.graphics.Color;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

import androidx.appcompat.widget.Toolbar;

import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.timmy.tdialog.TDialog;
import com.timmy.tdialog.base.BindViewHolder;
import com.timmy.tdialog.listener.OnBindViewListener;
import com.timmy.tdialog.listener.OnViewClickListener;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import cc.booku.owlbox.ArtDesign.SystemUtil;
import cc.booku.owlbox.FileOperations.FileoOperations;
import cc.booku.owlbox.R;

public class HomeDirectoryActivity extends AppCompatActivity {

    private Toolbar Toolbar;
    private List<HomeDirectory_C> homeDirectory_cList = new ArrayList<HomeDirectory_C>();
    private String filePath = Environment.getExternalStorageDirectory() + File.separator + "OwlDatabase" + File.separator;
    private ListView list_filename;
    private TextView fromfileurl;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home_directory);

        //加载标题栏
        LoadToolbar();
        //状态栏颜色
        SystemUtil.setStatusBarColor(this, Color.parseColor("#448aca"));

        list_filename = (ListView) findViewById(R.id.list_filename);
        fromfileurl = (TextView) findViewById(R.id.fromfileurl);
        fromfileurl.setText(filePath);
        //申请SD卡读写的权限
        FileoOperations.verifyStoragePermissions(HomeDirectoryActivity.this);
        //遍历该目录文件
        ReadDisplayDir(filePath);
    }

    public HomeDirectory_C homeDirectory_c;
    public HomeDirectory_A homeDirectory_a;

    private void ReadDisplayDir(String DirPath) {

        Log.e("111", "path" + DirPath);
        ArrayList<String> ss = FileoOperations.getFileName(DirPath, ".txt");
        for (String s : ss) {

            homeDirectory_c = new HomeDirectory_C();

            homeDirectory_c.setFireName(s);

            homeDirectory_cList.add(homeDirectory_c);

        }
        Message msg = new Message();
        msg.what = 9;
        handler.sendMessage(msg);//用activity中的handler发送消息

    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {

                case 9:
                    ClickFileName((ArrayList<HomeDirectory_C>) homeDirectory_cList);

                    break;
            }
        }
    };


    public void ClickFileName(ArrayList<HomeDirectory_C> fileName_cList) {

        homeDirectory_a = new HomeDirectory_A(R.layout.singlehome_item, HomeDirectoryActivity.this, fileName_cList);


        list_filename.setAdapter(homeDirectory_a);
        //点按操作
        list_filename.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                final TextView fileName = (TextView) view.findViewById(R.id.filename);
                String FileName = fileName.getText().toString();

                DialogFilechanges(filePath + FileName);

            }
        });


    }


    private void DialogFilechanges(final String FileUrl) {

        new TDialog.Builder(getSupportFragmentManager())
                .setLayoutRes(R.layout.tdialog_dired)
                .setScreenWidthAspect(this, 1.0f)
                .setGravity(Gravity.CENTER)
                .addOnClickListener(R.id.tv_show, R.id.tv_delete, R.id.tv_rename, R.id.tv_edit)
                .setOnViewClickListener(new OnViewClickListener() {
                    @Override
                    public void onViewClick(BindViewHolder viewHolder, View view, TDialog tDialog) {

                        switch (view.getId()) {
                            case R.id.tv_show:
                                //对文件重命名，添加“不显示_”
                                //修改1路径就可以
                                String blankurl = FileUrl.replace("OwlDatabase/不显示_", "OwlDatabase/");
                                FileoOperations.renameFile(FileUrl, blankurl);
                                tDialog.dismiss();
                                break;

                            case R.id.tv_rename:
                                String Str[] = FileUrl.split("OwlDatabase/");
                                DialogRename(Str[1]);
                                tDialog.dismiss();
                                break;

                            case R.id.tv_edit://编辑

                                Intent intent = new Intent(HomeDirectoryActivity.this, FileEditActivity.class);
                                //用Bundle携带数据
                                Bundle bundle = new Bundle();
                                //传递name参数为specifiedFile
                                bundle.putString("FileUrlName", FileUrl);
                                intent.putExtras(bundle);

                                startActivity(intent);
                                tDialog.dismiss();
                                break;

                            case R.id.tv_delete:
                                FileoOperations.deleteFile(HomeDirectoryActivity.this, FileUrl);

                                tDialog.dismiss();
                                break;

                        }
                        //更新listview
                        homeDirectory_cList.clear();
                        ReadDisplayDir(filePath);

                    }
                })

                .create()
                .show();
    }


    private void LoadToolbar() {
        //新页面接收数据


        Toolbar = (Toolbar) findViewById(R.id.toolbar);

        Toolbar.setTitle("根目录管理");

        setSupportActionBar(Toolbar);//利用Toolbar代替ActionBar
        Toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //跳转到用户设置页面
                finish();
            }
        });
        //添加menu 菜单点击事件
        Toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.action_folder_add:
                        //新建文件
                        //调用窗口
                        DialognewFile();
                        break;

                }
                return true;
            }
        });
    }


    @Override
    public boolean onCreatePanelMenu(int featureId, Menu menu) {
        getMenuInflater().inflate(R.menu.menu_folder_add, menu);//toolbar添加menu菜单
        return true;
    }


    private void DialogRename(final String Filename) {


        new TDialog.Builder(getSupportFragmentManager())
                .setLayoutRes(R.layout.tdialog_rename)
                .setScreenWidthAspect(this, 1.0f)
                .setGravity(Gravity.CENTER)
                .setOnBindViewListener(new OnBindViewListener() {   //通过BindViewHolder拿到控件对象,进行修改
                    @Override
                    public void bindView(BindViewHolder bindViewHolder) {
                        bindViewHolder.setText(R.id.editText, Filename);
                    }
                })
                .addOnClickListener(R.id.btn_cancel, R.id.btn_affirm)
                .setOnViewClickListener(new OnViewClickListener() {
                    @Override
                    public void onViewClick(BindViewHolder viewHolder, View view, TDialog tDialog) {


                        EditText editText = viewHolder.getView(R.id.editText);
                        String content = editText.getText().toString().trim();
                        switch (view.getId()) {
                            case R.id.btn_cancel:
                                tDialog.dismiss();
                                break;
                            case R.id.btn_affirm:
                                //String blankurl = content.replace("OwlDatabase/不显示_","OwlDatabase/");
                                FileoOperations.renameFile(filePath + Filename, filePath + content);
                                tDialog.dismiss();
                                break;

                        }


                    }
                })

                .create()
                .show();
    }


    private void DialognewFile() {

        new TDialog.Builder(getSupportFragmentManager())
                .setLayoutRes(R.layout.tdialog_newfile)
                .setScreenWidthAspect(this, 1.0f)
                .setGravity(Gravity.CENTER)
                .setOnBindViewListener(new OnBindViewListener() {   //通过BindViewHolder拿到控件对象,进行修改
                    @Override
                    public void bindView(BindViewHolder bindViewHolder) {

                        //获取系统时间
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日");// HH:mm:ss
//获取当前时间
                        Date date = new Date(System.currentTimeMillis());
                        // time1.setText("Date获取当前日期时间"+simpleDateFormat.format(date));

                        bindViewHolder.setText(R.id.editText, "标题_规范_分类_" + simpleDateFormat.format(date));
                    }
                })
                .addOnClickListener(R.id.btn_cancel, R.id.btn_affirm)
                .setOnViewClickListener(new OnViewClickListener() {
                    @Override
                    public void onViewClick(BindViewHolder viewHolder, View view, TDialog tDialog) {

                        EditText editText = viewHolder.getView(R.id.editText);
                        String content = editText.getText().toString().trim();
                        switch (view.getId()) {
                            case R.id.btn_cancel:

                                tDialog.dismiss();
                                break;
                            case R.id.btn_affirm:

                                //创建文件，并且刷新lixtview
                                FileoOperations.writeData(filePath, content, null);
                                tDialog.dismiss();
                                break;

                        }
                        homeDirectory_cList.clear();
                        ReadDisplayDir(filePath);


                    }
                })

                .create()
                .show();
    }


}
